<template>
  <div>
    <input type="file" @change="changes" ref="fileRef" />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import togeojson from "@mapbox/togeojson";
// import villageJson from "./village.json";
const fileRef = ref();

const changes = () => {
  // console.log(file, 'filefile')
  // console.log(fileRef.value.files[0], "fileRef.value");
  // console.log('触发啦啦啦')
  analysisKMLFile(fileRef.value.files[0]);
};
const analysisKMLFile = (file) => {
  // const reader = new FileReader()
  // console.log(reader.readAsText, 'reader.readAsText')
  let reader = new FileReader();
  // console.log(reader.readAsText, 'reader.readAsText')
  reader.readAsText(file, "utf-8");
  // reader.readAsText(file, 'utf-8')
  reader.onload = function (e) {
    const xml = new DOMParser().parseFromString(e.target.result, "text/xml");
    const geojson = togeojson.kml(xml, {
      style: true,
    });
    var nameRes = "";
    const failRes = [];
    geojson.features.forEach((i, j) => {
      const description = JSON.parse(
        "{" + i.properties.description.replace(/\n/g, ",") + "}"
      );
      // 过滤掉不是改区下的村庄数据
      if (String(description.code).substring(0, 6) == "220105") {
        if (i.geometry.coordinates && i.geometry.coordinates.length > 0) {
          const boundary = JSON.stringify(
            i.geometry.coordinates[0].map((k) => [k[1], k[0]])
          );
          if (i.geometry.coordinates?.[0]) {
            failRes.push({
              code: description.code,
              name: description?.name,
              boundary,
            });
            nameRes += `INSERT INTO area (code, name, parentId) VALUES ('${
              description.code
            }','${description?.name}','${String(description.code).substring(
              0,
              6
            )}');`;
          }
        } else if (i.geometry.geometries && i.geometry.geometries.length > 0) {
          const boundary = JSON.stringify(
            i.geometry.geometries[0].coordinates.map((k) => [k[1], k[0]])
          );
          if (i.geometry.geometries?.[0]) {
            failRes.push({
              code: description.code,
              name: description?.name,
              boundary,
            });
            nameRes += `INSERT INTO area (code, name, parentId) VALUES ('${
              description.code
            }','${description?.name}','${String(description.code).substring(
              0,
              6
            )}');`;
          }
        }
      }
    });
    console.log("sql", nameRes);
    console.log("json", failRes);
  };
};
onMounted(() => {
  // console.log(
  //   Object.entries(villageJson).map((i) => {
  //     return {
  //       id: i[0],
  //       name: i[1].name,
  //       code: "",
  //     };
  //   })
  // );
});
</script>
